package com.bestvike.stone.spring.quartz.core;

import com.bestvike.stone.spring.context.ThreadContext;
import com.bestvike.stone.spring.context.TraceContext;
import com.bestvike.stone.spring.trace.quartz.IncomingLog;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobListener;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.TriggerListener;
import org.springframework.util.Assert;

/**
 * Created by 许崇雷 on 2018-08-27.
 */
public final class DelegatingJob implements Job {
    private final Job delegate;

    /**
     * Create a instance of DelegatingJob
     *
     * @param delegate Job instance
     */
    public DelegatingJob(Job delegate) {
        Assert.notNull(delegate, "delegate can not be null");
        this.delegate = delegate;
    }

    /**
     * <p>
     * Called by the <code>{@link Scheduler}</code> when a <code>{@link Trigger}</code>
     * fires that is associated with the <code>Job</code>.
     * </p>
     *
     * <p>
     * The implementation may wish to set a
     * {@link JobExecutionContext#setResult(Object) result} object on the
     * {@link JobExecutionContext} before this method exits.  The result itself
     * is meaningless to Quartz, but may be informative to
     * <code>{@link JobListener}s</code> or
     * <code>{@link TriggerListener}s</code> that are watching the job's
     * execution.
     * </p>
     */
    @Override
    public void execute(JobExecutionContext context) {
        ThreadContext.init(null);
        TraceContext.init();
        String action = this.delegate.getClass().getName();
        IncomingLog.writeBeginLog(action);
        long begin = System.currentTimeMillis();
        try {
            this.delegate.execute(context);
            IncomingLog.writeEndLog(action, System.currentTimeMillis() - begin);
        } catch (Exception e) {
            IncomingLog.writeErrorLog(action, e, System.currentTimeMillis() - begin);
        } finally {
            TraceContext.reset();
            ThreadContext.reset();
        }
    }
}
